package com.JUC.cha05.setc01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class LockSupportDemo {

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t---- come in");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + "\t---- 被唤醒");
        }, "t1");
        t1.start();
        
        // 暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + "\t---- 通知");
        }, "t2").start();

    }

    private static void LockLockUnlock() {
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "---- come in ----");
                condition.await();
                System.out.println(Thread.currentThread().getName() + "---- 被唤醒 ----");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1").start();

        // 暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            lock.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + "---- 通知 ----");
            } finally {
                lock.unlock();
            }

        }, "t2").start();
    }

    private static void syncWaitNotify() {
        Object o = new Object();
        new Thread(() -> {
            synchronized (o) {
                System.out.println("---- come in ----");
                try {
                    o.wait();// wait阻塞，释放锁
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("---- o 被唤醒 ----");
            }

        }, "t1").start();

        // 暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            synchronized (o) {
                o.notify();
                System.out.println("---- 发出通知 ----");
            }

        }, "t2").start();
    }
}
